package com.xhl.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.xhl.service.CategoryService;
import com.xhl.util.SpringContextUtil;
import com.xhl.util.Utils;
import com.xhl.vo.CategoryVO;
import com.xhl.vo.Pager;

@Controller
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    CategoryService categoryService;

    @GetMapping(value = "/queryAll", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String queryCategoryAll(HttpServletRequest request) {
        List<CategoryVO> cvoList = categoryService.queryCategoryAll();
        String json = JSON.toJSONString(cvoList);
        return json;
    }

    @PostMapping(value = "/update", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public void updateCategory(String name, MultipartFile filepath, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String cid = req.getParameter("cid");

        if (cid == null) {
            return;
        }

        CategoryVO categoryVO = SpringContextUtil.getBean(CategoryVO.class);
        categoryVO.setCid(Integer.valueOf(cid));
        categoryVO.setName(name);
        categoryService.updateCategory(categoryVO);

        System.out.println(categoryVO);
        String imgname = cid + ".jpg";                        //新图片名称
        String realPath = "D:\\img\\category";
        System.out.println(filepath + " " + realPath + " " + imgname);
        Utils.upload(filepath, realPath, imgname);
        resp.sendRedirect("http://localhost:8080/#/admin/categoryList");
    }


    @GetMapping(value = "/query", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String queryCategory(HttpServletRequest request) {
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");
        if (pageNum == null) {
            return "异常";
        }
        @SuppressWarnings("unchecked")
        Pager<CategoryVO> p = SpringContextUtil.getBean(Pager.class);

        p.setSize(Integer.valueOf(pageSize));
        p.setPage((Integer.valueOf(pageNum) - 1) * Integer.valueOf(pageSize));
        List<CategoryVO> clist = categoryService.queryCategory(p);

        long count = categoryService.count();
        p.setTotal(count);
        p.setRows(clist);
        String json = JSON.toJSONString(p);
        return json;
    }

    @RequestMapping("/getImageCategory")
    @ResponseBody
    public void getCategory(HttpServletRequest rq, HttpServletResponse rp) {
        String cid = rq.getParameter("cid");
        if (cid == null) {
            return;
        }
        String filePath = "D:\\img\\category\\" + cid + ".jpg";
        Utils.showImg(rp, filePath);
    }

    // 图片上传
    @RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody // 不写会默认返回当前路径！！
    public void upload(String name, MultipartFile filepath, HttpServletRequest req, HttpServletResponse resp)
            throws Exception, IOException {
        if (name == null) {
            return;
        }

        categoryService.addCategory(name);

        long maxId = categoryService.queryMax();

        System.out.println("username 数据：" + name + " 最大id  " + maxId);

        // 接收文件数据
        System.out.println(filepath.getContentType());                // image/jpeg 获取上传文件的类型
        System.out.println(filepath.getName());                        // image 获取file标签的name属性 <input type="file" name="image" >
        //String filename = filepath.getOriginalFilename();			//原来图片名称
        //String nameSuffix = FilenameUtils.getExtension(filename); 	// FilenameUtils.getExtension 获取后缀名
        String imgname = maxId + ".jpg";                        //新图片名称
        System.out.println(imgname);
        // 获取到上传的文件数据
        String contentType = filepath.getContentType();
        // 判断上传文件是否为图片
        if (contentType == null || !contentType.startsWith("image/")) {
            System.out.println("===不属于图片类型...===");
            return;
        }

        String realPath = "D:\\img\\category";
        Utils.upload(filepath, realPath, imgname);
        resp.sendRedirect("http://localhost:8080/#/admin/categoryList");
    }


    @RequestMapping(value = "/delete", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String deleteCategory(HttpServletRequest rq, HttpServletResponse rp) {
        String cid = rq.getParameter("cid");
        if (cid == null) {
            return "";
        }
        System.out.println("删除成功   " + cid);
        categoryService.deleteCategory(cid);
        return "删除成功";
    }


}
